package com.hanxiaozhang.example.producerfunction;

import com.hanxiaozhang.constant.RocketConstant;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.selector.SelectMessageQueueByHash;
import org.apache.rocketmq.client.producer.selector.SelectMessageQueueByMachineRoom;
import org.apache.rocketmq.client.producer.selector.SelectMessageQueueByRandom;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.remoting.common.RemotingHelper;

import java.io.UnsupportedEncodingException;

/**
 * 〈一句话功能简述〉<br>
 * 〈选择发送队列〉
 *
 * @author hanxinghua
 * @create 2023/6/28
 * @since 1.0.0
 */
public class No1SelectSendQueueNode {

    public static void main(String[] args) throws Exception {

        DefaultMQProducer producer = new DefaultMQProducer(RocketConstant.ORIGINAL_PRODUCER_GROUP);
        producer.setNamesrvAddr(RocketConstant.NAME_SERVER_ADDR);
        producer.start();
        // 方式一、指定 queueId 来选择具体的队列  Ext：BrokerName配置在broker.conf中
        Message message1 = new Message(RocketConstant.ORIGINAL_TOPIC, ("way one").getBytes(RemotingHelper.DEFAULT_CHARSET));
        MessageQueue messageQueue1 = new MessageQueue(RocketConstant.ORIGINAL_TOPIC, "broker-a", 0);
        producer.send(message1, messageQueue1);

        // 方式二、根据 MessageQueueSelector 策略来选择队列
        // RocketMQ内部定义了三种 MessageQueueSelector 策略：
        // + SelectMessageQueueByHash：基于方法参数arg的哈希值，对队列总数取模，选择对应下标的队列。
        // + SelectMessageQueueByRandom：基于队列总数生成一个随机数，选择对应下标的队列。
        // + SelectMessageQueueByMachineRoom：基于机房选择队列。这个未实现，还是要通过自己的场景进行实现。
        Message message2_1 = new Message(RocketConstant.ORIGINAL_TOPIC, ("way two byHash").getBytes(RemotingHelper.DEFAULT_CHARSET));
        producer.send(message2_1, new SelectMessageQueueByHash(), "hash");

        Message message2_2 = new Message(RocketConstant.ORIGINAL_TOPIC, ("way two byRandom").getBytes(RemotingHelper.DEFAULT_CHARSET));
        producer.send(message2_2, new SelectMessageQueueByRandom(), "random");

        Message message2_3 = new Message(RocketConstant.ORIGINAL_TOPIC, ("way two byMachineRoom").getBytes(RemotingHelper.DEFAULT_CHARSET));
        producer.send(message2_3, new SelectMessageQueueByMachineRoom(), "machineRoom");

        // 方式三、基于Broker的可用性采取轮询的策略选择队列
        // DefaultMQProducer的send() 或 sendOneway() ，可以不携带MessageQueue、MessageQueueSelector，内部调用：
        // MessageQueue mqSelected = this.selectOneMessageQueue(topicPublishInfo, lastBrokerName);


    }

}
